<template>
  <div class="cart">
      <cart-item v-for="(item,index) in items" 
                 :ordinal="index+1"
                 :item="item"
                 :key="item.id"
                 :decrease="handleDecrease"
                 :increase="handleIncrease"
                 @删除="handleRemove">
      </cart-item>
      <cart-total>{{ totalPrice }}</cart-total>
  </div>
</template>

<script>
// 导入组件
import CartItem from './CartItem.vue';
import CartTotal from './CartTotal.vue';

export default {
    name: 'ShoppingCart',
    data(){
        return {
            items: [
                { id: 12 , name: '藜蒿炒腊肉' , price: 50 , amount: 50 },
                { id: 10 , name: '荷包辣椒荷包蛋' , price: 28 , amount: 100 },
                { id: 11 , name: '毛血旺' , price: 26 , amount: 150 },
                { id: 27 , name: '回锅肉' , price: 40 , amount: 20 }
            ]
        }
    },
    methods: {
        // 删除指定的购物车项
        handleRemove( id ){
            // 寻找被删除项目在数组中的位置
            let index = this.items.findIndex( e => e.id == id );
            // 从数组中删除 index 处单个元素
            this.items.splice( index , 1 );
        },
        // 让指定购物车项中的商品数量减少
        handleDecrease( id ){
            let item = this.items.find( e => e.id == id );
            if( item && item.amount > 1 ) {
                item.amount-- ;
            }
        },
        // 让指定购物车项中的商品数量增加
        handleIncrease( id ){
            let item = this.items.find( e => e.id == id );
            if( item ) {
                item.amount++ ;
            }
        }
    },
    computed: {
        totalPrice(){
            let total = this.items.reduce( (p,c) => p + c.price * c.amount , 0 );
            return total.toLocaleString('zh-CN',{ style: 'currency' , currency: 'CNY' });
        }
    },
    components: {
        'cart-item': CartItem,
        'cart-total': CartTotal
    }
}
</script>

<style>
.cart { margin: 15px auto; border: 1px solid green; width: 80%; }
.item .operation a ,
.total-wrapper .settle a {
    display: inline-block;
    border-radius: 2px;
    padding: 5px;
    cursor: pointer;
    line-height: 16px;
    font-size: 14px;
    color: #fff;
    background: rgb(75, 75, 255);
    user-select: none;
}
.item .operation a:hover ,
.total-wrapper .settle a:hover { background: rgb(26, 26, 229);}
</style>